package socket

import (
	"common/models"
	"common/validate"
	"common/websocket"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
	"project/docModel"
	"project/pkg/dao/redis"
	"time"
)

// map [form-to:cID]
//
// handleConnection 用户使用聊天
func (h SHandler) handleConnection(c websocket.Connection) {
	socketMsg := new(websocket.MessageText)
	zap.L().Info(c.ID())
	h.socket.UserSelfMsg("登录成功", c, []byte("1"))
	i := 0
	//获得用户的信息
	c.OnMessage(func(msg []byte) {
		zap.L().Info(string(msg))
		json.Unmarshal(msg, socketMsg)
		//将userID放入Map -redis
		for i == 0 {
			if !socketMsg.Group {
				h.socket.UserIDs.Store(socketMsg.GetConnectName(), c.ID())
				h.R.SetString(redis.SocketCid+c.ID(), socketMsg.GetConnectName(), 5*time.Minute)
				h.socket.UserSelfMsg("初始化成功", c, []byte("1"))
				//查redis获得对应的聊天记录
				value, _ := h.R.GetAllValue(redis.FormToMsg + socketMsg.GetRedisConnectName())
				if len(value) != 0 {
					//发送全部消息
					for _, s := range value {
						data := []byte(s)
						oldMsg := new(websocket.MessageText)
						json.Unmarshal(data, oldMsg)
						fmt.Println(oldMsg.Msg)
						if oldMsg.Msg == "" {
							continue
						}
						h.socket.UserSelfOldMsg(c, data)
					}
				}
			} else {
				//如果是群聊模式
				h.socket.UserIDs.Store(socketMsg.GetConnectName(), c.ID())
				h.R.SetString(redis.SocketCid+c.ID(), socketMsg.GetConnectName(), 5*time.Minute)
				h.socket.UserSelfMsg("初始化成功", c, []byte("1"))
				//查看是否群的聊天室是否存在，存在直接加入没有创建加入
				h.socket.Join(websocket.Group+socketMsg.GroupId, c.ID())
				//查redis获取群聊的历史信息
				value, _ := h.R.GetAllValue(redis.GroupToMsg + socketMsg.GroupId)
				if len(value) != 0 {
					//发送全部消息
					for _, s := range value {
						data := []byte(s)
						oldMsg := new(websocket.MessageText)
						json.Unmarshal(data, oldMsg)
						fmt.Println(oldMsg.Msg)
						if oldMsg.Msg == "" {
							continue
						}
						h.socket.UserSelfOldMsg(c, data)
					}
				}
				i++
			}
		}
		if socketMsg.Msg != "" {
			if !socketMsg.Group {
				//发送消息
				h.socket.UserSendMsg(socketMsg)
				//将消息放道redis的数组里面
				//将结构体序列化
				marshal, _ := json.Marshal(socketMsg)
				h.R.PushListRight(redis.FormToMsg+socketMsg.GetRedisConnectName(), string(marshal), 10*time.Minute)
			} else {
				//发送消息
				h.socket.UserSendMsg(socketMsg)
				//将结构体序列化
				marshal, _ := json.Marshal(socketMsg)
				h.R.PushListRight(redis.GroupToMsg+socketMsg.GroupId, string(marshal), 10*time.Minute)
			}
		}
	})
	c.OnDisconnect(func() {
		str := "断开连接" + c.ID()
		zap.L().Info(str)
		//从redis读取
		uid, err := h.R.GetString(redis.SocketCid + c.ID())
		if err != nil {
			zap.L().Info("h.R.GetString", zap.Error(err))
		}
		h.socket.UserIDs.Delete(uid)
		h.socket.UserClose(uid)
	})
	return
}
func (h SHandler) delOldMsg(c *gin.Context) {
	//删除历史消息
	resp := new(models.RespData)
	req := new(docModel.DelOldMsgReq)
	if err := c.ShouldBindJSON(req); err != nil {
		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			zap.L().Error("Socket:delOldMsg with invalid fail", zap.Error(err))
			resp.SendServerBusy(c)
			return
		} else {
			zap.L().Error("Socket:delOldMsg with invalid fail", zap.Error(errs))
			resp.SendCodeWithMsg(c, models.CodeInvalidParam, validate.RemoveTopStruct(errs.Translate(validate.Trans)))
			return
		}
	}
	msg := websocket.MessageText{
		From: req.From,
		To:   req.To,
	}
	if err := h.R.DelList(redis.FormToMsg + msg.GetRedisConnectName()); err != nil {
		resp.SendServerBusy(c)
		return
	}
	resp.SendSuccess(c)
}
